import COM.CCB.EnDecryptAlgorithm.MCipherEncryptor;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author xiexiaojin
 * @date 2025-02-23 10:21
 */
public class diancan {
    private static String qrcode = "9500000053696697540988"; //CCB9916240105897384114540

    private static String shl_id="temp6982091"; //5320001
    private static String st_id="13434185552"; //W202403019
    private static String ECARDEVID="100001";
    private static String BRANCHID="370000000";
    private static String MERCHANTID="105910000509210"; //105000448160540
    private static String POSID="071984009";
    private static String TrdPt_Pltfrm_OrCd="8024";
    private static String MERFLAG="1";
    private static String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

    public static void main(String[] args) throws Exception{
        String sc = "https://app.xiaoyuan.ccb.com/backstageService";//生产环境
        String strKey = "dukZFRXOGXaJ4BViue9YpHbpGRUVzhl2";  //广州南方学院番禺附属中学一卡通密钥
//        String strKey = "v8erZL/BMop240y2a8LL1b/Hq2S/wTKK";   //体验学校一卡通密钥

        //获取token
        String loginMid="/device/login?schoolId="+shl_id+"&ccbParam=";
        String loginStr = login();
        MCipherEncryptor ccbEncryptor = new MCipherEncryptor(strKey.substring(strKey.length() - 30));
        loginStr = ccbEncryptor.doEncrypt(loginStr);
        String jsonStr=sendRequest("",sc+loginMid+loginStr);
        JSONObject response = JSON.parseObject(jsonStr).getJSONObject("data");
        String token = response.getString("token");
        if(response!=null && !response.isEmpty()){
           token= response.getString("token");
        }


//        String mid="/device/getDeviceInfo?schoolId="+shl_id+"&ccbParam=";  //修改请求的接口
//        //加密
//        String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzY2hvb2xJZCI6IjEwMDAxIiwic2hvcElkIjoiRURGMjQ4RUREREJGQzAxRkUwNTM5MzQ5RkQwQTFGOTEiLCJleHAiOjE3NDM1MjMyMDAsImRldmljZUlkIjoiMjJlM2YxZmMzNDQ3NDkwNzk1ZDFhZTJjZGM2MDQ3NzEiLCJhY2NvdW50IjoicGNpX3Rlc3QifQ.rCe3GvDybPBasHDF2EwyRljMQeiCJJGJLlkftRnwWFM" ;
//        String jsonInputString = getDeviceInfo();
//        MCipherEncryptor ccbEncryptor = new MCipherEncryptor(strKey.substring(strKey.length() - 30));
//        jsonInputString = ccbEncryptor.doEncrypt(jsonInputString);
//        sendRequest("",sc+mid+jsonInputString);
//        System.out.println(sc+mid+jsonInputString);


        String mid="/dishes/getReleaseDishes?schoolId="+shl_id+"&ccbParam=";  //修改请求的接口
        //加密
//        String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzY2hvb2xJZCI6IjEwMDAxIiwic2hvcElkIjoiRURGMjQ4RUREREJGQzAxRkUwNTM5MzQ5RkQwQTFGOTEiLCJleHAiOjE3NDI1NzI4MDAsImRldmljZUlkIjoiMjJlM2YxZmMzNDQ3NDkwNzk1ZDFhZTJjZGM2MDQ3NzEiLCJhY2NvdW50IjoicGNpX3Rlc3QifQ.W1ZcRO3em3KeAyIRn9DF8pkOzMPit0nbc9sM4t6Bnk0" ;
        String jsonInputString = getReleaseDishes();
        MCipherEncryptor ccbEncryptor1 = new MCipherEncryptor(strKey.substring(strKey.length() - 30));
        jsonInputString = ccbEncryptor1.doEncrypt(jsonInputString);
        sendRequest(token,sc+mid+jsonInputString);
        System.out.println(sc+mid+jsonInputString);

    }

    /**
     * 餐别同步
     */
    public static String mealType(){
        String schoolId = shl_id;
        String tm = String.valueOf(System.currentTimeMillis()); // 当前时间戳
        // 准备JSON格式的请求体
        String jsonInputString = String.format("{\"schoolId\":\"%s\",\"tm\":\"%s\"}",
                schoolId, tm);
        System.out.println(jsonInputString);
        return jsonInputString;
    }

    /**
     * 获取一周内已发布菜品接口
     */
    public static String getWeekReleaseDishes(){
        String schoolId = shl_id;
        String releaseStartDate = "2025-04-01";  //发布开始时间（yyyy-MM-dd）
        String releaseEndDate = "2025-04-02";  //发布结束时间（yyyy-MM-dd）
        String tm = String.valueOf(System.currentTimeMillis()); // 当前时间戳
        // 准备JSON格式的请求体
        String jsonInputString = String.format("{\"schoolId\":\"%s\",\"releaseStartDate\":\"%s\",\"releaseEndDate\":\"%s\",\"tm\":\"%s\"}",
                schoolId, releaseStartDate, releaseEndDate, tm);
//        System.out.println("请求数据："+jsonInputString);
        return jsonInputString;
    }
    /**
     * 对菜品上下架
     */
//    public static String updateReleaseDishesStatus(){
//        String schoolId = shl_id;
//        String deviceCode = "133D002000700030";  //设备编号
//        String tm = String.valueOf(System.currentTimeMillis()); // 当前时间戳
//        Json json = new Json("[\n" +
//                "        {\n" +
//                "            \"releaseDishesId\": \"c76248d45e7e4e918167bd4a1564d05f\", \n" +
//                "            \"status\": 0\n" +
//                "        }, \n" +
//                "        {\n" +
//                "            \"releaseDishesId\": \"566faad683a84d8a955b05bddbf75b85\", \n" +
//                "            \"status\": 0\n" +
//                "        }\n" +
//                "    ]");
//        // 准备JSON格式的请求体
//        String jsonInputString = String.format("{\"schoolId\":\"%s\",\"releaseDishesList\":\"%s\",\"tm\":\"%s\"}",
//                schoolId, json, tm);
//        System.out.println(jsonInputString);
//        return jsonInputString;
//    }
    /**
     * 获取已发布菜品接口
     */
    public static String getReleaseDishes(){
        String schoolId = shl_id;
        String releaseDate = "2025-04-02";  //发布时间（yyyy-MM-dd）
        String mealTypeId="F65B46D1F04F11B7E0539349FD0ACE7E";  //餐别id
        String tm = String.valueOf(System.currentTimeMillis()); // 当前时间戳
        // 准备JSON格式的请求体
        String jsonInputString = String.format("{\"schoolId\":\"%s\",\"releaseDate\":\"%s\",\"mealTypeId\":\"%s\",\"tm\":\"%s\"}",
                schoolId, releaseDate, mealTypeId, tm);
        System.out.println(jsonInputString);
        return jsonInputString;
    }

    /**
     * 终端操作员登录接口
     */
    public static String login(){
        String schoolId = shl_id;
//        String deviceId = "22e3f1fc3447490795d1ae2cdc604771";  //设备id 体验学校
//        String account = "pci_test";  //操作员账号
//        String password = "Pci@2025"; //操作员密码
        String deviceId = "9951ce8847a1423f957d461487cc8a50";  //设备id 南方学院
        String account = "operator";  //操作员账号
        String password = "PCIccb15!"; //操作员密码
        String tm = String.valueOf(System.currentTimeMillis()); // 当前时间戳
        // 准备JSON格式的请求体
        String jsonInputString = String.format("{\"schoolId\":\"%s\",\"deviceId\":\"%s\",\"account\":\"%s\",\"password\":\"%s\",\"tm\":\"%s\"}",
                schoolId, deviceId, account,password, tm);
        System.out.println(jsonInputString);
        return jsonInputString;
    }
    /**
     * 获取设备信息接口
     */
    public static String getDeviceInfo(){
        String schoolId = shl_id;
//        String deviceCode = "133D002000700030";  //设备编号  体验学校
        String deviceCode = "114D002001200006";  //设备编号  南方学院
        String tm = String.valueOf(System.currentTimeMillis()); // 当前时间戳
        // 准备JSON格式的请求体
        String jsonInputString = String.format("{\"schoolId\":\"%s\",\"deviceCode\":\"%s\",\"tm\":\"%s\"}",
                schoolId, deviceCode, tm);
        System.out.println(jsonInputString);
        return jsonInputString;
    }

    /**
     * 发送请求
     */
    public static String sendRequest(String token,String urlpath) {
        StringBuffer responseBuffer = new StringBuffer();
        try {
            // 请求地址
            URL url = new URL(urlpath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            if(token!=null&&!"".equals(token)){
                conn.setRequestProperty("token",  token); // 设置token
            }
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);
            conn.connect();


            // 读取响应
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 这里可以读取响应体内容
                BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
                String tmp;
                while ((tmp=br.readLine())!=null){
                    responseBuffer.append(tmp).append("\n");
                }
                br.close();
            } else {
                // 处理错误响应
                System.out.println("GET Request Failed with Error code : " + responseCode);
            }

            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(responseBuffer);
        return responseBuffer.toString();
    }

}
